<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>websocket 聊天</title>
  <style>
    * {margin: 0;padding: 0;box-sizing: border-box;}
    html,body,.wrapper{width: 100%;height: 100%;}
    ul,li{margin-left: 20px;}
    .wrapper{padding: 10px;}
    .content{padding: 10px;float: left;width: 49.5%;min-height: 300px;border: 1px solid #ddd;}
    .content:nth-child(1) {margin-right: 1%;}
    h3{margin-bottom: 10px;}
    .message {width: 60%;text-align:center;line-height: 40px;font-size: 20px;border-radius: 5px;border: 1px solid #B3D33F;}
    .message:focus{outline-color: #f00;}
    .connect {cursor: pointer;width: 80px;height: 40px;vertical-align: top;font-size: 20px;border-radius: 5px; color: #fff;border: none;background: #B3D33F;}
  </style>
</head>
<body>
  <div class="wrapper">
    <div class="content">
      <h3>接受socket信息:</h3>
      <ul id="response"></ul>
    </div>
    <div class="content" >
      <h3>发送信息:</h3>
      <input type="text" placeholder="请输入发送的消息" class="message" id="message"/>
      <button id="send" class="connect">发送</button>
      <button id="connect" class="connect">连接</button>
    </div>
  </div>
  <script>
    var oUl = document.getElementById('response')
    var oConnect = document.getElementById('connect')
    var oSend = document.getElementById('send')
    var oInput = document.getElementById('message')
    var ws = null;
    oConnect.onclick = function () {
      if(!ws) {
        ws = new WebSocket('ws://localhost:5000')
      }
      ws.onopen = function () {
        oUl.innerHTML += "<li>客户端已连接</li>"
      }
      ws.onmessage = function (evt) {
        oUl.innerHTML += "<li>" + evt.data + "</li>"
      }
      ws.onclose = function () {
        oUl.innerHTML += "<li>客户端已断开连接</li>"
      }
      ws.onerror = function (evt) {
        oUl.innerHTML += "<li>" + evt.data + "</li>"
      }
    }
    oSend.onclick = function () {
      if(!oInput.value) {
        let type = confirm('请输入要发送的消息')
        type && oInput.focus()
        return
      }
      if (ws) {
        ws.send(oInput.value)
      }
    }
  </script>
</body>
</html>